const WebSocket = require('ws');
const { Client } = require('whatsapp-web.js');

const wsUrl = process.argv[2];
if (!wsUrl) {
    console.error('请提供 WebSocket 地址作为参数。');
    process.exit(1);
}

// 创建 WebSocket 连接
const ws = new WebSocket(wsUrl);
const client = new Client();

// 心跳检测和重连机制
const HEARTBEAT_INTERVAL = 30000; // 30秒
let heartbeatIntervalId = null;
let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 5; // 最大重连尝试次数

function sendHeartbeat() {
    if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: 'heartbeat' }));
    }
}

function startHeartbeat() {
    heartbeatIntervalId = setInterval(sendHeartbeat, HEARTBEAT_INTERVAL);
}

function stopHeartbeat() {
    clearInterval(heartbeatIntervalId);
}

function reconnect() {
    if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
        reconnectAttempts++;
        console.log(`尝试第 ${reconnectAttempts} 次重连...`);
        ws = new WebSocket(wsUrl);
        // 重新绑定事件处理器
        initWebSocket();
    } else {
        console.error('达到最大重连次数，停止重连');
    }
}

function initWebSocket() {
    ws.on('open', function open() {
        console.log(`连接成功：${wsUrl}`);
        startHeartbeat(); // 开始心跳
        sendSysMsg('连接成功');
    });

    ws.on('message', function incoming(data) {
        console.log('收到消息：', data.toString());
        // 处理消息
    });

    ws.on('error', function error(err) {
        console.error('连接错误：', err);
    });

    ws.on('close', function close() {
        console.log('连接关闭');
        stopHeartbeat(); // 停止心跳
        reconnect(); // 尝试重连
    });
}

// 初始化 WebSocket 事件处理器
initWebSocket();

// 监听 'message' 事件，转发消息
client.on('message', msg => {
    console.log(msg);
    reUserMsg(msg);
    msg.reply(`XiaoHe ${new Date()}`);
});

// 监听 'ready' 事件
client.on('ready', () => {
    sendSysMsg('Client is ready!');
});

// 监听 'qr' 事件
client.on('qr', (qr) => {
    console.log('QR RECEIVED', qr);
    sendSysMsg(qr);
});

// 定义发送用户消息的函数
function reUserMsg(msg) {
    const message = {
        msg_id: msg.id.id,
        acc_id: msg.to,
        msg: msg.body,
        from_id: msg.from,
        from_name: msg.notifyName,
        cy_id: null,
        acc_type: 'whatsapp',
        msg_type: msg.type === 'chat' ? 0 : 1,
        cy_name: null
    };
    ws.send(JSON.stringify(message));
}

// 定义发送系统消息的函数
function sendSysMsg(msg) {
    const systemMessage = {
        msg_id: 111,
        acc_id: 111,
        msg: msg,
        from_id: 1,
        from_name: '系统信息',
        cy_id: 1,
        acc_type: 'whatsapp',
        msg_type: 0,
        cy_name: 'system'
    };
    ws.send(JSON.stringify(systemMessage));
}

client.initialize();